local GenieList = GenieList

function GenieList:CreateBorder(item_frame)
  if (item_frame.border) then
    return
  end
  -- Create the border with proper properties.
  local border = item_frame:CreateTexture(nil, 'OVERLAY')
  border:SetTexture('Interface\\Addons\\GenieList\\GenieList_Highlight')
  border:SetBlendMode('BLEND')
  border:SetAlpha(1.0)

  -- Set its dimensions.
  border:SetWidth(70)
  border:SetHeight(70)

  -- Set its location.
  border:SetPoint('TOPLEFT', item_frame, 'TOPLEFT', -10, 15)
  item_frame.border = border
end

function GenieList:OnQuestFrameUpdate(quest_state)
  -- Quest log is treated separately.
  local is_quest_log = 0
  if (quest_state == 'QuestLog') then
    is_quest_log = 1
  end

  -- Obtain the number of rewards in different categories.
  local num_quest_choices = 0
  local num_quest_spell_rewards = 0
  local num_quest_rewards = 0
  if (is_quest_log == 1) then
    num_quest_rewards = GetNumQuestLogRewards()
    num_quest_choices = GetNumQuestLogChoices()
    if (GetQuestLogRewardSpell()) then
      numQuestSpellRewards = 1
    end
  else
    num_quest_rewards = GetNumQuestRewards()
    num_quest_choices = GetNumQuestChoices()
    if (GetRewardSpell()) then
      numQuestSpellRewards = 1
    end
  end

  local total_rewards = num_quest_rewards +
                        num_quest_spell_rewards +
                        num_quest_choices
  local quest_item_name = quest_state..'Item'

  -- Now to through all rewards and update them.
  local item_frame
  local item_name
  local i
  for i = 1, total_rewards, 1 do
    -- Obtain item frame using global index.
    item_frame = getglobal(quest_item_name..i)

    -- Obtain item name using local index based on reward type.
    if (i <= num_quest_choices) then
      -- Choice rewards.
      if (is_quest_log == 1) then
        item_name = GetQuestLogChoiceInfo(i)
      else
        item_name = GetQuestItemInfo('choice', i)
      end
    elseif (i > num_quest_choices + num_quest_spell_rewards) then
      -- Rewards. Notice that we skip the spell rewards.
      local index = i - num_quest_choices - num_quest_spell_rewards
      if (is_quest_log == 1) then
        item_name = GetQuestLogRewardInfo(index)
      else
        item_name = GetQuestItemInfo('reward', index)
      end
    end

    if (self.db.profile.highlight_item and self.db.char.items[item_name]) then
      -- This item is on the wishlist, create a border for it if needed.
      self:CreateBorder(item_frame)
      -- Show the border.
      item_frame.border:Show()
    else
      -- The item is not on the wishlist, if we have a border for it, we need
      -- to make sure it is hidden.
      if (item_frame.border) then
        item_frame.border:Hide()
      end
    end
  end
end

QuestFrame:HookScript('OnUpdate', function(self)
  GenieList:OnQuestFrameUpdate('QuestReward')
end)
QuestLogDetailScrollFrame:HookScript('OnUpdate', function(self)
  GenieList:OnQuestFrameUpdate('QuestLog')
end)
